using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using CommunityToolkit.Mvvm.Messaging;
using DialogHostAvalonia;
using Microsoft.Extensions.DependencyInjection;
using SchoolApp_Material.Msgs;
using SchoolApp_Material.ViewModels;

namespace SchoolApp_Material.Views;

public partial class StudentMgrView : UserControl
{
    public StudentMgrView()
    {
        InitializeComponent();
        DataContext = Program.ServiceProvider.GetRequiredService<StudentMgrViewModel>();
    }

    private void StudentMgrView_Loaded(object sender, RoutedEventArgs e)
    {
        WeakReferenceMessenger.Default.Register<MsgBase<StudentViewModel>>(this, async (r, msg) =>
        {
            var formEditViewModel = Program.ServiceProvider.GetRequiredService<StudentEditViewModel>();
            formEditViewModel.InitData(msg.Data);
            var result = await DialogHost.Show(
                new StudentEditView { DataContext = formEditViewModel },
                "MainWindowHost");
            if (result is true)
            {
                if (msg.Data.Id == 0)
                {
                    //新增
                }
                else
                {
                    //修改
                }

                btnQuery.Command?.Execute(null);
            }
        });
        WeakReferenceMessenger.Default.Register<StudentDelMsg>(this, async (r, msg) =>
        {
            var result = await DialogHost.Show(
                new MsgBoxView
                {
                    DataContext = new MsgBoxViewModel()
                    {
                        MsgBoxIcon = MsgBoxIcons.Warning,
                        Title = "删除提示",
                        Content = $"确认要删除[{msg.Student.Code}]数据记录吗",
                        MsgBoxShowButton = MsgBoxShowButtons.YesNo,
                        DefaultEnter = MsgBoxButtons.Yes,
                        DefaultEscape = MsgBoxButtons.No,
                    }
                },
                "MainWindowHost");
            if (result is MsgBoxButtons msgBoxButton)
            {
                if (msgBoxButton == MsgBoxButtons.Yes)
                {
                    msg.ConfirmAction?.Invoke();
                }
                else
                {
                }
            }
        });
        btnQuery.Command?.Execute(null);
    }

    private void StudentMgrView_Unloaded(object sender, RoutedEventArgs e)
    {
        WeakReferenceMessenger.Default.Unregister<MsgBase<StudentViewModel>>(this);
    }
}